import re

from django.shortcuts import redirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin


class ShopMiddleware(MiddlewareMixin):
    def __init__(self, get_response):
        # print("ShopMiddleware")
        self.get_response = get_response

    def __call__(self, request):
        path = request.path
        # print("url:", path)

        # 判断后台是否登陆
        # 判断当前请求的url地址是否以/pet_admin开头，并且不在加白列表urllist中
        urllist = ['/pet_admin/login', '/pet_admin/dologin', '/pet_admin/logout', '/pet_admin/verify']
        if re.match(r'^/pet_admin', path) and (path not in urllist):
            # 判断是否登陆
            if "adminUser" not in request.session:
                return redirect(reverse("admin_login"))

        # 判断前台是否登陆
        # 判断当前请求的url地址是否以/pet_web开头
        if re.match(r'^/pet_web', path):
            # 判断是否登陆
            if "webUser" not in request.session:
                return redirect(reverse("web_login"))
        response = self.get_response(request)

        return response
